package com.ncmmall.application.business.order;

import com.feijin.commons.lang.ArithUtils;
import com.ncmmall.domain.business.cloudstore.CloudStoreGoods;
import com.ncmmall.domain.business.cloudstore.CloudStoreGoodsRepository;
import com.ncmmall.domain.business.cloudstore.QCloudStoreGoods;
import com.ncmmall.domain.business.express.Express;
import com.ncmmall.domain.business.express.QExpress;
import com.ncmmall.domain.business.merchant.freight.MerchantFreight;
import com.ncmmall.domain.business.merchant.freight.MerchantFreightTemplate;
import com.ncmmall.domain.business.merchant.freight.QMerchantFreight;
import com.ncmmall.domain.business.merchant.freight.QMerchantFreightTemplate;
import com.ncmmall.domain.business.order.lading.BillOfLading;
import com.ncmmall.domain.business.order.lading.BillOfLadingDetail;
import com.ncmmall.domain.business.order.lading.BillOfLadingDetailRepository;
import com.ncmmall.domain.business.order.lading.BillOfLadingRepository;
import com.ncmmall.domain.business.order.lading.QBillOfLading;
import com.ncmmall.domain.business.trading.TradingLog;
import com.ncmmall.domain.business.trading.TradingLogRepository;
import com.ncmmall.domain.security.user.QWebUser;
import com.ncmmall.domain.security.user.WebUser;
import com.ncmmall.domain.security.user.WebUserRepository;
import com.ncmmall.querychannel.service.QueryChannelService;
import com.google.common.base.Splitter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author linxs
 * @Description: 云仓提货单业务
 * @Date: 2020-05-13 13:50
 */
@Service
@Transactional
public class BillLadingApplication {

    @Autowired
    private BillOfLadingRepository billOfLadingRepository;

    @Autowired
    private BillOfLadingDetailRepository billOfLadingDetailRepository;

    @Autowired
    private CloudStoreGoodsRepository cloudStoreGoodsRepository;

    @Autowired
    private WebUserRepository userRepository;

    @Autowired
    private TradingLogRepository tradingLogRepository;

    @Autowired
    private QueryChannelService queryChannelService;

    /**
     * 创建云仓提货单
     */
    public void create(BillOfLading billOfLading) {

        billOfLading.setCreateTime(new Timestamp(System.currentTimeMillis()));
        billOfLading.setStatus(1);

        String orderNo = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) + billOfLading.getMerchant().getId();

        billOfLading.setOrderNo(orderNo);


        billOfLadingRepository.save(billOfLading);

        double price = 0;

        List<String> data = Splitter.on(";").omitEmptyStrings().trimResults().splitToList(billOfLading.getData());
        for (String item : data) {
            long id = Long.parseLong(item.substring(0, item.indexOf(":")));
            int quantity = Integer.parseInt(item.substring(item.indexOf(":") + 1));

            CloudStoreGoods cloudStoreGoods = queryChannelService.findOne(QCloudStoreGoods.cloudStoreGoods.id.eq(id), CloudStoreGoods.class);
            cloudStoreGoods.setQuantity(cloudStoreGoods.getQuantity() - quantity);
            if (cloudStoreGoods.getQuantity() <= 0) {
                cloudStoreGoods.setStatus(2);
            }

            cloudStoreGoodsRepository.save(cloudStoreGoods);

            BillOfLadingDetail detail = new BillOfLadingDetail();
            detail.setBillOfLading(billOfLading);
            detail.setCloudStoreGoods(cloudStoreGoods);
            detail.setQuantity(quantity);
            billOfLadingDetailRepository.save(detail);

            double freightPrice = 0;

            if (cloudStoreGoods.getGoods().getSupplierPostageType() == 1) {     //走运费模板

                MerchantFreight freight = queryChannelService.findOne(QMerchantFreight.merchantFreight.city.eq(billOfLading.getDeliveryCity()).and(QMerchantFreight.merchantFreight.merchant.eq(billOfLading.getSupplier()).and(QMerchantFreight.merchantFreight.template.id.eq(cloudStoreGoods.getGoods().getSupplierFreightTemplate().getId()))), MerchantFreight.class);

                MerchantFreightTemplate template = queryChannelService.findOne(QMerchantFreightTemplate.merchantFreightTemplate.id.eq(cloudStoreGoods.getGoods().getSupplierFreightTemplate().getId()), MerchantFreightTemplate.class);

                //按重量
                if (template.getType() == 1) {
                    if (null != freight) {   //拿到了模板内设置的区域运费
                        double gram = ArithUtils.mul(cloudStoreGoods.getGoods().getGram(), quantity);//总重量
                        if (gram <= freight.getFirstWeight()) {
                            freightPrice = freight.getFirstWeightAmount();
                        } else {
                            freightPrice = ArithUtils.add(freight.getFirstWeightAmount(), ArithUtils.mul(ArithUtils.div(ArithUtils.sub(gram, freight.getFirstWeight()), freight.getOtherWeight(), 2), freight.getOtherWeightAmount()));
                        }
                    } else {
                        double gram = ArithUtils.mul(cloudStoreGoods.getGoods().getGram(), quantity);//总重量
                        if (gram <= template.getDefaultWeight()) {
                            freightPrice = template.getDefaultWeightAmount();
                        } else {
                            freightPrice = ArithUtils.add(template.getDefaultWeightAmount(), ArithUtils.mul(ArithUtils.div(ArithUtils.sub(gram, template.getDefaultWeight()), template.getDefaultAddWeight(), 2), template.getDefaultAddWeightAmount()));
                        }
                    }
                }

                //按件
                if (template.getType() == 2) {
                    if (null != freight) {
                        if (quantity <= freight.getFirstPiece()) {
                            freightPrice = freight.getFirstPieceAmount();
                        } else {
                            freightPrice = ArithUtils.add(freight.getFirstPieceAmount(), ArithUtils.mul(ArithUtils.sub(quantity, freight.getFirstPiece()), freight.getOtherPieceAmount()));
                        }
                    } else {
                        if (quantity <= template.getDefaultPiece()) {
                            freightPrice = template.getDefaultPieceAmount();
                        } else {
                            freightPrice = ArithUtils.add(template.getDefaultPieceAmount(), ArithUtils.mul(ArithUtils.sub(quantity, template.getDefaultPiece()), template.getDefaultAddPieceAmount()));
                        }
                    }
                }
            } else if (cloudStoreGoods.getGoods().getSupplierPostageType() == 2) {      //包邮
                freightPrice = ArithUtils.add(freightPrice, 0);
            } else if (cloudStoreGoods.getGoods().getSupplierPostageType() == 3) {       //指定运费
                freightPrice = ArithUtils.add(freightPrice, ArithUtils.mul(cloudStoreGoods.getGoods().getSupplierPostage(), quantity));
            }

            price += freightPrice;

        }

        billOfLading.setPrice(price);
        if (billOfLading.getPrice() == 0) {
            billOfLading.setStatus(2);
            billOfLading.setPayStatus(1);
        }
        billOfLadingRepository.save(billOfLading);
    }

    /**
     * 提货单运费支付成功
     */
    public void wechatPaySuccess(BillOfLading billOfLading) {
        billOfLading.setPayStatus(1);
        billOfLading.setStatus(2);
        billOfLading.setPayTime(new Timestamp(System.currentTimeMillis()));
        billOfLading.setPayMethod(1);
        billOfLadingRepository.save(billOfLading);
    }

    /**
     * 提货单出库（发货）
     */
    public void delivery(BillOfLading params) {

        BillOfLading billOfLading = queryChannelService.findOne(QBillOfLading.billOfLading.id.eq(params.getId()), BillOfLading.class);

        Express express = queryChannelService.findOne(QExpress.express.expressCompanyCode.eq(params.getExpressCode()), Express.class);

        billOfLading.setExpressCompany(express.getName());
        billOfLading.setExpressesNo(params.getExpressesNo());
        billOfLading.setExpressCode(express.getExpressCompanyCode());

        billOfLading.setStatus(3);
        billOfLading.setDeliveryTime(new Timestamp(System.currentTimeMillis()));
        billOfLadingRepository.save(billOfLading);

    }

    /**
     * 提货单签收
     */
    public void finish(BillOfLading billOfLading) {

        billOfLading.setStatus(4);
        billOfLading.setFinishTime(new Timestamp(System.currentTimeMillis()));
        billOfLading.setReceiptTime(new Timestamp(System.currentTimeMillis()));
        billOfLadingRepository.save(billOfLading);


        WebUser supplier = queryChannelService.findOne(QWebUser.webUser.id.eq(billOfLading.getSupplier().getId()), WebUser.class);
        supplier.setBalance(ArithUtils.add(supplier.getBalance(), billOfLading.getPrice()));
        userRepository.save(supplier);

        TradingLog tradingLog2 = new TradingLog();
        tradingLog2.setCreateTime(new Timestamp(System.currentTimeMillis()));
        tradingLog2.setMerchant(supplier);
        tradingLog2.setStatus(1);
        tradingLog2.setType(6);
        tradingLog2.setAmount(billOfLading.getPrice());
        tradingLog2.setOrderNo(billOfLading.getOrderNo());
        tradingLogRepository.save(tradingLog2);

    }
}
